package com.ywk.zzh.mongotest.aspect;



import com.ywk.zzh.mongotest.document.User;
import com.ywk.zzh.mongotest.util.SnowflakeIdGenerator;
import lombok.AllArgsConstructor;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Aspect
@Component
@AllArgsConstructor
public class InsertAspect {

    private final SnowflakeIdGenerator snowflakeIdGenerator;

    @Before("@annotation(com.ywk.zzh.mongotest.annotate.GenerateInsert) && args(user)")
    public void generateBeforeSave(JoinPoint joinPoint, User user) {
        // 检查ID是否为空
        if (user.getId() == null) {
            // 生成雪花算法ID
            long id = snowflakeIdGenerator.nextId();
            user.setId(id);
        }
        // 检查删除标志字段是否为空
        if (user.getDelFlag() == null) {
            user.setDelFlag(0);
        }
        // 检查创建时间和更新时间字段是否为空
        if (user.getCreateTime() == null) {
            user.setCreateTime(LocalDateTime.now());
        }
        if (user.getUpdateTime() == null) {
            user.setUpdateTime(LocalDateTime.now());
        }
    }
}
